const treeData = require("./treeData")


//宽度优先递归复制一颗树，实际上内容也用到了深度优先遍历先计算树的深度
function copyTreeByLayer(node){
    if(!node){
        return
    }
    function getMaxDepth(node){//深度优先遍历实现求解树的最大深度
        if(!node){
            return 0
        }
        // console.log("value:",node.value)
        if(node.children.length === 0){
            return 1
        }
        const depthValues = []
        for(let i = 0; i < node.children.length; i++){
            depthValues.push(getMaxDepth(node.children[i]))
        }
        return 1 +  Math.max(...depthValues)
    }
    function collectCurrentLevelNodes(node,level,current_level_nodes){//按层递归遍历树
        if(!node){
            return
        }
        if(level === 1){
            current_level_nodes.push(node)
        }else if(level > 1){
            for(let j = 0; j < node.children.length;j++){
                collectCurrentLevelNodes(node.children[j],level - 1,current_level_nodes)
            }
        }
    }
    const maxDepth = getMaxDepth(node)  //基于深度优先递归获取树的最大深度，即最大层数
    console.log("maxDepth:", maxDepth)
    for(let i = 1; i <= maxDepth; i++ ){//按层遍历树上的各个节点
        let current_level_nodes = []
        collectCurrentLevelNodes(node,i,current_level_nodes)
        console.log("第" + i + "层：",JSON.stringify(current_level_nodes))
    }
   
   
}


function testCopyTreeByLayered(){
    const tree = treeData.getTree()
    copyTreeByLayer(tree)
}
testCopyTreeByLayered()




